package com.lxr0860.lxr0860production_test;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.res.AssetFileDescriptor;
import android.hardware.Camera;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.net.NetworkInfo;
import android.net.wifi.ScanResult;
import android.net.wifi.WifiConfiguration;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.SystemClock;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.GridView;
import android.widget.TextView;

import com.lxr0860.lxr0860production_test.adapter.FactoryTestIemAdapter;
import com.lxr0860.lxr0860production_test.bean.FactoryTestItem;
import com.lxr0860.lxr0860production_test.itemactivity.AudioActivity;
import com.lxr0860.lxr0860production_test.itemactivity.BluTest;
import com.lxr0860.lxr0860production_test.itemactivity.FlashActivity;
import com.lxr0860.lxr0860production_test.itemactivity.GPSActivity;
import com.lxr0860.lxr0860production_test.itemactivity.GprsActivity;
import com.lxr0860.lxr0860production_test.itemactivity.ICC_0860Activity;
import com.lxr0860.lxr0860production_test.itemactivity.InfoActivity;
import com.lxr0860.lxr0860production_test.itemactivity.KeyActivity;
import com.lxr0860.lxr0860production_test.itemactivity.LCDActivity;
import com.lxr0860.lxr0860production_test.itemactivity.LEDActivity;
import com.lxr0860.lxr0860production_test.itemactivity.LightSensorActivity;
import com.lxr0860.lxr0860production_test.itemactivity.MicActivity;
import com.lxr0860.lxr0860production_test.itemactivity.PCIE_TestActivity;
import com.lxr0860.lxr0860production_test.itemactivity.PhotoReviewAcitivty;
import com.lxr0860.lxr0860production_test.itemactivity.PorintTestActivity;
import com.lxr0860.lxr0860production_test.itemactivity.ScanActivity;
import com.lxr0860.lxr0860production_test.itemactivity.TFActivity;
import com.lxr0860.lxr0860production_test.itemactivity.TPActivity;
import com.lxr0860.lxr0860production_test.itemactivity.USBActivity;
import com.lxr0860.lxr0860production_test.itemactivity.WifiActivity;
import com.lxr0860.lxr0860production_test.itemactivity.ZDActivity;
import com.lxr0860.lxr0860production_test.utils.Contants;
import com.lxr0860.lxr0860production_test.utils.FileUtils;
import com.lxr0860.lxr0860production_test.utils.SharedPreferencesUtils;
import com.sdk.devicemanager.LTEcon;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by 11 on 2018/3/21.
 */

public class TestItemActivity extends Activity {

    private GridView mGvTestItems;
    private TextView mTvTopTitle;
    private TextView mTvDiwenTip;
    private int testType;
    private List<FactoryTestItem> testItems;
    private FactoryTestIemAdapter mAdapter;
    private BluetoothAdapter mBluetoothAdapter;
    private int currentPosition;
    private static final int REQUST_CODE_MAIN = 100;
    private static final int UPDATE_UI = 1;
    private File file_log;
    private boolean destroy;
    private UpdateUiThread mThread;
//    private int diwen_time_delay = 2 * 60 * 60;
    private int diwen_time_delay = 2;

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case UPDATE_UI:
                    if (mAdapter != null) {
                        mAdapter.notifyDataSetChanged();
                    }
                    break;
                case MSG_WIFI_COMPLETE:
                    if (receiveSuccessCount == WIFI_TEST_COUNT && sendSuccessCount == WIFI_TEST_COUNT) {
                        mTvDiwenTip.setText("正在进行音频测试...");
                        prepareMusic();
                    } else {
                        mTvDiwenTip.setText("WIFI测试失败");
                    }
                    break;
                case Contants.DIALOG_POSITIVE:
                    realseMusic();
                    File file = new File(Contants.LOG_DIWEN_DELAY_PATH);
                    if (!file.exists()) {
                        try {
                            file.createNewFile();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                    mGvTestItems.setVisibility(View.VISIBLE);
                    changeAppBrightness(200);
                    mTvDiwenTip.setVisibility(View.GONE);
                    if (mThread == null) {
                        mThread = new UpdateUiThread();
                        mThread.start();
                    }
                    break;
                case Contants.DIALOG_NEGATIVE:
                    realseMusic();
                    finish();
                    break;
            }
        }
    };

    private Runnable diwenTimeRunnable = new Runnable() {
        @Override
        public void run() {
            diwen_time_delay--;
            if (diwen_time_delay > 30 * 60) {
                mTvDiwenTip.setText(formatDiwenTime(diwen_time_delay));
            } else if (diwen_time_delay == 30 * 60) {
                mTvDiwenTip.setText("正在进行WIFI测试...");
                testWifi();
            } else if (diwen_time_delay == 0) {

                Contants.showDailog(TestItemActivity.this, "音频是否还正常播放", handler, Gravity.CENTER);
            }
            handler.postDelayed(this, 1000);
        }
    };

    private String formatDiwenTime(int time) {
        int hour = time / 60 / 60;
        int min = (time - hour * 60 * 60) / 60;
        int second = time - hour * 60 * 60 - min * 60;
        return String.format("倒计时：%02d:%02d:%02d", hour, min, second);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.activity_test_item);
        initView();
        initData();
        initEvent();
    }


    private void initView() {
        mGvTestItems = (GridView) findViewById(R.id.gv_test_items);
        mTvTopTitle = (TextView) findViewById(R.id.tv_top_title);
        mTvDiwenTip = (TextView) findViewById(R.id.tv_diwen_tip);
    }

    private void initData() {
        mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        testItems = new ArrayList<FactoryTestItem>();
        testType = getIntent().getIntExtra("testType", Contants.TEST_ZUZHUANG);
        String title = Contants.getTopTitle(testType);
        mTvTopTitle.setText(title);
        mAdapter = new FactoryTestIemAdapter(this, testItems);
        mGvTestItems.setAdapter(mAdapter);
        if (testType == Contants.TEST_DIWEN) {
            File file = new File(Contants.LOG_DIWEN_DELAY_PATH);
            if (!file.exists()) {
                getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
                changeAppBrightness(1);
                mGvTestItems.setVisibility(View.GONE);
                mTvDiwenTip.setVisibility(View.VISIBLE);
                mTvDiwenTip.setText(formatDiwenTime(diwen_time_delay));
                handler.postDelayed(diwenTimeRunnable, 1000);
                return;
            }
        }
        mGvTestItems.setVisibility(View.VISIBLE);
        mTvDiwenTip.setVisibility(View.GONE);
        if (mThread == null) {
            mThread = new UpdateUiThread();
            mThread.start();
        }
    }

    private void initEvent() {
        mAdapter.setOnGridButtonClickListener(new FactoryTestIemAdapter.OnGridButtonClickListener() {
            @Override
            public void startNextActivity(int position) {
                bleSuccess = false;
                Intent intent = null;
                currentPosition = position;
                switch (testItems.get(position).getTestId()) {

                    case Contants.TEST_ITEM_INFO:
                        intent = new Intent(TestItemActivity.this, InfoActivity.class);
                        break;
                    case Contants.TEST_ITEM_LCD:
                        intent = new Intent(TestItemActivity.this, LCDActivity.class);
                        break;
                    case Contants.TEST_ITEM_TP:
                        intent = new Intent(TestItemActivity.this, TPActivity.class);
                        break;
                    case Contants.TEST_ITEM_KEY:
                        intent = new Intent(TestItemActivity.this, KeyActivity.class);
                        break;
                    case Contants.TEST_ITEM_WIFI:
                        intent = new Intent(TestItemActivity.this, WifiActivity.class);
                        break;
                    case Contants.TEST_ITEM_IC:
                        intent = new Intent(TestItemActivity.this, ICC_0860Activity.class);
                        break;
                    case Contants.TEST_ITEM_SCAN:
                        intent = new Intent(TestItemActivity.this, ScanActivity.class);

                        break;
                    case Contants.TEST_ITEM_BLUETOOTH:
//                        if (mBluetoothAdapter.getName() != null
//                                && mBluetoothAdapter.getName().equals("s1")) {
//                            intent = new Intent(TestItemActivity.this, BLEPeripheralActivity.class);
//                        } else {
//                            intent = new Intent(TestItemActivity.this, BLECentral2Activity.class);
//                        }
                        intent = new Intent(TestItemActivity.this, BluTest.class);
                        break;
                    case Contants.TEST_ITEM_AUDIO:
                        intent = new Intent(TestItemActivity.this, AudioActivity.class);
                        break;
                    case Contants.TEST_ITEM_TF:
                        intent = new Intent(TestItemActivity.this, TFActivity.class);
                        break;
                    case Contants.TEST_ITEM_USB:
                        intent = new Intent(TestItemActivity.this, USBActivity.class);
                        break;
                    case Contants.TEST_ITEM_FLASH:
                        intent = new Intent(TestItemActivity.this, FlashActivity.class);
                        break;
                    case Contants.TEST_ITEM_CAMERA:
                        intent = new Intent(TestItemActivity.this, PhotoReviewAcitivty.class);
                        intent.putExtra("cameraId", Camera.CameraInfo.CAMERA_FACING_BACK);
                        break;
                    case Contants.TEST_FONT_CAMERA:
                        intent = new Intent(TestItemActivity.this, PhotoReviewAcitivty.class);
                        intent.putExtra("cameraId", Camera.CameraInfo.CAMERA_FACING_FRONT);
                        break;
                    case Contants.TEST_ITEM_GPRS:
                        intent = new Intent(TestItemActivity.this, GprsActivity.class);
                        break;
                    case Contants.TEST_ITEM_GPS:
                        intent = new Intent(TestItemActivity.this, GPSActivity.class);
                        break;
                    case Contants.TEST_ITEM_LIGHT_SENSOR:
                        intent = new Intent(TestItemActivity.this, LightSensorActivity.class);
                        break;
                    case Contants.TEST_ITEM_MIC:
                        intent = new Intent(TestItemActivity.this, MicActivity.class);
                        break;
                    case Contants.TEST_ITEM_PCIE:
                        intent = new Intent(TestItemActivity.this, PCIE_TestActivity.class);
//                        intent = new Intent(TestItemActivity.this, PCIEActivity.class);
                        break;
                    case Contants.TEST_ITEM_LED:
                        intent = new Intent(TestItemActivity.this, LEDActivity.class);
                        break;
                    case Contants.TEST_ITEM_ZD:
                        intent = new Intent(TestItemActivity.this, ZDActivity.class);
                        break;
                    case Contants.TEST_ITEM_POINT:
                        intent = new Intent(TestItemActivity.this, PorintTestActivity.class);
                        break;
                    /*case Contants.TEST_ITEM_FINGER:
                        intent = new Intent(TestItemActivity.this, FingerActivity.class);
                        break;

                    case Contants.TEST_ITEM_NFC:
                        intent = new Intent(TestItemActivity.this, NfcActivity.class);
                        break;
                    case Contants.TEST_ITEM_SYSTEM:
                        intent = new Intent(TestItemActivity.this, SystemActivity.class);
                        break;
                    case Contants.TEST_ITEM_UHF:
                        intent = new Intent(TestItemActivity.this, UhfActivity.class);
                        break;

                    case Contants.TEST_ITEM_PROXIMITY_SENSOR:
                        intent = new Intent(TestItemActivity.this, ProximitySensorActivity.class);
                        break;
                    case Contants.TEST_ITEM_ACCELEROMETER:
                        intent = new Intent(TestItemActivity.this, AccelerometerActivity.class);
                        break;
                    case Contants.TEST_ITEM_PHONE:
                        intent = new Intent(TestItemActivity.this, PhoneActivity.class);
                        break;*/

                }
                intent.putExtra("testType", testType);
                TestItemActivity.this.startActivityForResult(intent, REQUST_CODE_MAIN);
//                TestItemActivity.this.startActivity(intent);
            }
        });
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        destroy = true;
        getWindow().clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        handler.removeCallbacks(diwenTimeRunnable);
        releaseWifi();
        realseMusic();
        if (mThread != null) {
            mThread.interrupt();
            mThread = null;
        }

        String itemState = "";
        for (FactoryTestItem testItem : testItems) {
            itemState = itemState+Contants.itemTitlesTest[testItem.getTestId()]+testItem.getTestState()+" ";
        }
        Log.e("itemState",itemState);
        String saveKey = "0";
        switch (testType){
            case 0:
                saveKey = Contants.ZZCJ;
                break;
            case 1:
                saveKey = Contants.ZDCS;
                break;
            case 2:
                saveKey = Contants.FSCS;
                break;
            case 3:
                saveKey = Contants.DWCS;
                break;
            case 4:
                saveKey = Contants.GWCS;
                break;
            case 5:
                saveKey = Contants.CPJY;
                break;
            case 6:
                saveKey = Contants.CPCJ;
                break;
        }

        //保存测试记录
        SharedPreferencesUtils.saveData(this,saveKey,itemState);

    }

    @Override
    protected void onActivityResult(int requestCode, final int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUST_CODE_MAIN) {
            if (data != null && data.getBooleanExtra("result", false)) {
                testItems.get(currentPosition).setCanTest(false);
                testItems.get(currentPosition).setTestState(Contants.ItemTestState_Success);
                boolean testComplete = false;
                for (int i = 0; i < testItems.size(); i++) {
                    if (testItems.get(i).isCanTest()) {
                        testComplete = false;
                        SharedPreferencesUtils.saveData(this,Contants.TestState,"fail");
                        break;
                    } else {
                        testComplete = true;
                        SharedPreferencesUtils.saveData(this,Contants.TestState,"success");
                    }
                }
                final String testLog = testComplete ?
                        testType + "" + resultCode + "\r\ntrue\r\n" : testType + "" + resultCode + "\r\n";
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        FileUtils.writeFile(file_log.getAbsolutePath(), testLog);
                    }
                }).start();
                if (mAdapter != null) {
                    mAdapter.notifyDataSetChanged();
                }
                if (testComplete) {
                    Intent mIntent = new Intent();
                    Bundle bundle = new Bundle();
                    bundle.putBoolean("result", true);
                    mIntent.putExtras(bundle);
                    TestItemActivity.this.setResult(testType, mIntent);
                    finish();
                }
            }else{
                //测试失败的记录
                testItems.get(currentPosition).setTestState(Contants.ItemTestState_Fail);
            }
        }
    }

    private class UpdateUiThread extends Thread {
        @SuppressLint("MissingPermission")
        @Override
        public void run() {
            file_log = new File(Contants.LOG_FACTORY_PATH + File.separator + "" + testType + ".txt");
            for (int i = 0; i < Contants.itemTitles.length; i++) {
                if (destroy) {
                    return;
                }
                FactoryTestItem item = new FactoryTestItem(Contants.itemTitles[i],
                        true, Contants.getItemBtnBgId(i), i);
                if (Contants.TEST_ITEM_BLUETOOTH == i) {
                    if (mBluetoothAdapter.getName() != null
                            && mBluetoothAdapter.getName().equals("s1")) {
                        item.setCanTest(true);
                    }
                }
                if (SharedPreferencesUtils.getBooleanData(TestItemActivity.this,Contants.itemTitles[i], true)) {
                    testItems.add(item);
                }
                if (Contants.TEST_ITEM_INFO == i &&
                        (testType != Contants.TEST_CHENGPIN && testType != Contants.TEST_ZUZHUANG)&& testType != Contants.TEST_CPCJ) {
                    testItems.remove(item);
                }
//                if (Contants.TEST_ITEM_USB == i &&
//                        (testType == Contants.TEST_DIWEN || testType == Contants.TEST_GAOWEN)) {
//                    testItems.remove(item);
//                }
//                if (Contants.TEST_ITEM_SCAN == i && testType == Contants.TEST_DIWEN) {
//                    testItems.remove(item);
//                }
            }
            if (!file_log.exists() || !file_log.isFile()) {
                handler.sendEmptyMessage(UPDATE_UI);
                return;
            }
            BufferedReader bufr = null;
            try {
                bufr = new BufferedReader(new FileReader(file_log));
                String line;
                while ((line = bufr.readLine()) != null) {
                    if (destroy) {
                        return;
                    }
                    Log.e("cly", "line=" + line);
                    if (line.length() > 0 && !line.equals("true")) {
                        if (line.substring(0, 1).equals(testType + "")) {
                            int index = 0;
                            for (int i = 0; i < testItems.size(); i++) {
                                if (testItems.get(i).getTestId() ==
                                        Integer.parseInt(line.substring(1))) {
                                    index = i;
                                    break;
                                }
                            }
                            testItems.get(index).setCanTest(false);
                        }
                    }
                }
                bufr.close();
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                if (bufr != null) {
                    try {
                        bufr.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
            handler.sendEmptyMessage(UPDATE_UI);
        }
    }


    //---------------------wifi-------------------------------
    private WifiManager wifiManager;
    private NetReceiver myNetReceiver;
    private LTEcon mLtecon;
    private static final int WIFI_TEST_COUNT = 6000;
    private static final int WIFI_STATE_CONNECTED = 1;
    private static final int MSG_WIFI_COMPLETE = 2;
    private int connectState;
    private Socket socket;
    private int sendSuccessCount, sendFailCount, receiveSuccessCount, receiveFailCount;
    private boolean isProcess, isScanFinished;
    private WifiThread mWifiThread;
    OutputStream osSend = null;
    InputStream isRead = null;

    private void testWifi() {
        //关闭4G
        mLtecon = new LTEcon(TestItemActivity.this);
        mLtecon.poweroff();
        //wifi
        wifiManager = (WifiManager) this.getSystemService(Context.WIFI_SERVICE);
        IntentFilter filter = new IntentFilter();
        filter.addAction(WifiManager.WIFI_STATE_CHANGED_ACTION);
        filter.addAction(WifiManager.NETWORK_STATE_CHANGED_ACTION);
        filter.addAction(WifiManager.RSSI_CHANGED_ACTION);
        filter.addAction(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION);
        myNetReceiver = new NetReceiver();
        registerReceiver(myNetReceiver, filter);//注册监听WIFI连接成功与否
        openWifi();
    }

    private void openWifi() {
        Log.e("cly", "openWifi");
        if (!wifiManager.isWifiEnabled()) {
            wifiManager.setWifiEnabled(true);
        } else if (wifiManager.getWifiState() == WifiManager.WIFI_STATE_ENABLED) {
            connectWifi();
        }
    }
    @SuppressLint("MissingPermission")
    private void connectWifi() {
        Log.e("cly", "connectWifi");
        boolean exsit = false;
         List<ScanResult> scanResults = wifiManager.getScanResults();
        Log.e("cly", "scanResult.size-->" + scanResults.size());
        for (ScanResult scanResult : scanResults) {
            Log.e("cly", "scanResult-->" + scanResult.SSID);
            if (scanResult.SSID.equals("uniriho")) {
                exsit = true;
                break;
            }
        }
        if (!exsit) {
            mTvDiwenTip.setText("未搜索到uniriho热点");
            return;
        }
        Log.e("cly", "connectWifi");
        WifiConfiguration exitConfig = isMyWifiExit("uniriho");
        if (exitConfig != null) {
            wifiManager.enableNetwork(exitConfig.networkId, true);
        } else {
            WifiConfiguration wifiConfiguration = createWifiInfo("uniriho", "uniriho03");
            wifiManager.enableNetwork(wifiConfiguration.networkId, true);
        }
    }

    private WifiConfiguration isMyWifiExit(String ssid) {
        Log.e("cly", "isMyWifiExit--" + ssid);
        //已配置好的网络
        @SuppressLint("MissingPermission") List<WifiConfiguration> configuredNetworks = wifiManager.getConfiguredNetworks();
        for (WifiConfiguration configuration : configuredNetworks) {
            if (configuration.SSID.equals("\"" + ssid + "\"")) {
                return configuration;
            }
        }
        return null;
    }

    public WifiConfiguration createWifiInfo(String SSID, String Password) {
        Log.e("cly", "createWifiInfo--" + SSID + "--" + Password);
        WifiConfiguration configuration = new WifiConfiguration();
        configuration.allowedAuthAlgorithms.clear();
        configuration.allowedGroupCiphers.clear();
        configuration.allowedKeyManagement.clear();
        configuration.allowedPairwiseCiphers.clear();
        configuration.allowedProtocols.clear();
        configuration.SSID = "\"" + SSID + "\"";
        //wap加密
        configuration.preSharedKey = "\"" + Password + "\"";
        configuration.hiddenSSID = true;
        configuration.allowedAuthAlgorithms.set(WifiConfiguration.AuthAlgorithm.OPEN);
        configuration.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP);
        configuration.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP);
        configuration.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_PSK);
        configuration.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.CCMP);
        configuration.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.TKIP);
        configuration.status = WifiConfiguration.Status.ENABLED;
        wifiManager.addNetwork(configuration);
        return configuration;
    }

    private void startWifiTest() {
        Log.e("cly", "startWifiTest");
        if (!isProcess) {
            if (mWifiThread == null) {
                mWifiThread = new WifiThread();
                mWifiThread.start();
            }
        }
    }

    private class NetReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (action.equals(WifiManager.NETWORK_STATE_CHANGED_ACTION)) {
                NetworkInfo info = intent.getParcelableExtra(WifiManager.EXTRA_NETWORK_INFO);
                if (info.getState().equals(NetworkInfo.State.CONNECTED)) {
                    if (connectState == WIFI_STATE_CONNECTED) {
                        return;
                    }
                    Log.e("cly", "STATE_CHANGED--CONNECTED");
                    connectState = WIFI_STATE_CONNECTED;
                    WifiInfo wifiInfo = wifiManager.getConnectionInfo();
                    startWifiTest();
                }
            } else if (action.equals(WifiManager.WIFI_STATE_CHANGED_ACTION)) {
                int extra = intent.getIntExtra(WifiManager.EXTRA_WIFI_STATE, 0);
                switch (extra) {
                    case WifiManager.WIFI_STATE_ENABLED:
                        Log.e("cly", "WIFI_STATE_ENABLED");
                        wifiManager.startScan();
                        break;
                    case WifiManager.WIFI_STATE_DISABLED:
                        Log.e("cly", "WIFI_STATE_DISABLED");
                        break;
                    case WifiManager.WIFI_STATE_ENABLING:
                        Log.e("cly", "WIFI_STATE_ENABLING");
                        break;
                }
            } else if (action.equals(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION)) {
                Log.e(":cly", "扫描完毕");
                if (isScanFinished) {
                    return;
                }
                isScanFinished = true;
                connectWifi();
            }
        }
    }


    private class WifiThread extends Thread {
        @Override
        public void run() {
            isProcess = true;
            try {
                Thread.sleep(500);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            if (connectServer()) {
                if (socket != null) {
                    try {
                        //发送
                        String step = "abcdefghijklmnopqrstuvwxy";
                        String receive = "0123456789";
                        String send = null;
                        for (int m = 0; m < 40; m++) {
                            send += step;
                        }
                        final long testStartTime = SystemClock.elapsedRealtime();
                        for (int i = 0; i < WIFI_TEST_COUNT; i++) {
                            if (destroy) {
                                isProcess = false;
                                return;
                            }
                            if (socket.isConnected() && !socket.isClosed()) {
                                if (osSend == null) {
                                    //发送byte字节数据
                                    osSend = socket.getOutputStream();
                                }
                                if (isRead == null) {
                                    isRead = socket.getInputStream();
                                }
                                //写byte字节数据
                                osSend.write(((send + jy(step)).substring(4)).getBytes());
                                //准备接收服务器反馈dateok
                                osSend.flush();
                                String sendResult = "";
                                // 客户端接收服务器端的响应，读取服务器端向客户端的输入流
                                long startSendTime = SystemClock.elapsedRealtime();
                                while (true) {
                                    if (destroy) {
                                        return;
                                    }
                                    if (SystemClock.elapsedRealtime() - startSendTime >= 3 * 1000) {
                                        break;
                                    }
                                    if (isRead.available() > 0) {
                                        break;
                                    }
                                }
                                byte[] sendBuf = new byte[isRead.available()];
                                isRead.read(sendBuf);
                                sendResult = new String(sendBuf);
                                if (sendResult.equals("dateok")) {
                                    sendSuccessCount++;
                                } else {
                                    sendFailCount++;
                                }
                            } else {
                                Log.e("cly", "socket异常");
                            }
                            if (socket.isConnected() && !socket.isClosed()) {
                                osSend.write(receive.getBytes());  //写byte字节数据
                                osSend.flush();
                                String receiveRuslt = "";
                                long startSendTime = SystemClock.elapsedRealtime();
                                while (true) {
                                    if (destroy) {
                                        return;
                                    }
                                    if (SystemClock.elapsedRealtime() - startSendTime >= 3 * 1000) {
                                        break;
                                    }
                                    if (isRead.available() > 0) {
                                        break;
                                    }
                                }
                                byte[] receivebuf = new byte[isRead.available()];
                                isRead.read(receivebuf);
                                receiveRuslt = new String(receivebuf);
                                if (receiveRuslt.length() == 1004) {
                                    receiveSuccessCount++;
                                } else {
                                    receiveFailCount++;
                                }
                            } else {
                                Log.e("cly", "socket异常");
                            }
                        }
                        handler.sendEmptyMessage(MSG_WIFI_COMPLETE);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    isProcess = false;
                }
            } else {
                isProcess = false;
            }
            releaseWifi();
        }
    }

    private boolean connectServer() {
        if (socket == null) {
            socket = new Socket();
        }
        if (socket.isConnected()) {
            return true;
        }
        try {
            socket.connect(new InetSocketAddress("120.79.19.49", 6669), 5000);
            socket.setTcpNoDelay(true);
            socket.setKeepAlive(true);
            return socket.isConnected();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return false;
    }

    private void releaseWifi() {
        if (mWifiThread != null) {
            mWifiThread.interrupt();
            mWifiThread = null;
        }
        if (osSend != null) {
            try {
                osSend.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        if (isRead != null) {
            try {
                isRead.close();
                isRead = null;
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        if (socket != null) {
            try {
                socket.close();
                socket = null;
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        if (myNetReceiver != null) {
            unregisterReceiver(myNetReceiver);
            myNetReceiver = null;
        }
        if (wifiManager != null && wifiManager.getWifiState() != WifiManager.WIFI_STATE_DISABLED) {
            wifiManager.setWifiEnabled(false);
        }
    }

    /**
     * 校验码
     *
     * @param str
     * @return
     */
    public int jy(String str) {
        byte[] bytesB = str.getBytes();
        int sum = 0;//求和
        for (int j = 0; j < 40; j++) {
            for (int i = 0; i < bytesB.length; i++) {
                sum += bytesB[i];
            }
        }
        int jiaoyanma = sum % 10000;//那么和10000取余就可以得到后四位
        if (jiaoyanma < 1000) {//当小于四位数的时候，就每次给他乘以10也就是在末尾添0
            jiaoyanma *= 10;
        }
        return jiaoyanma;
    }

    //音频播放
    private boolean stopByUser;
    private MediaPlayer mMediaPlayer;
    public static boolean bleSuccess = false;

    private void prepareMusic() {
        AudioManager audiomanage = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
        int maxVolume = audiomanage.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
        audiomanage.setStreamVolume(AudioManager.STREAM_MUSIC, maxVolume, AudioManager.FLAG_SHOW_UI);
        if (mMediaPlayer == null) {
            mMediaPlayer = new MediaPlayer();
        } else {
            mMediaPlayer.reset();
        }
        try {
            AssetFileDescriptor fileDescriptor = getAssets().openFd("qijideshan.mp3");
            mMediaPlayer.setDataSource(fileDescriptor.getFileDescriptor(),
                    fileDescriptor.getStartOffset(),
                    fileDescriptor.getLength());
            mMediaPlayer.prepare();
            mMediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
                @Override
                public void onCompletion(MediaPlayer mp) {
                    Log.e("cly", "onCompletion");
                    if (stopByUser) {
                        mp.stop();
                    } else {
                        prepareMusic();
                    }
                }
            });
            startMusic();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private void startMusic() {
        if (!mMediaPlayer.isPlaying()) {
            mMediaPlayer.start();
        }
    }

    private void realseMusic() {
        stopByUser = true;
        if (mMediaPlayer != null) {
            mMediaPlayer.stop();
            mMediaPlayer.reset();
            mMediaPlayer.release();
            mMediaPlayer = null;
        }
    }

    public void changeAppBrightness(int brightness) {
        Window window = this.getWindow();
        WindowManager.LayoutParams lp = window.getAttributes();
        if (brightness == -1) {
            lp.screenBrightness = WindowManager.LayoutParams.BRIGHTNESS_OVERRIDE_NONE;
        } else {
            lp.screenBrightness = (brightness <= 0 ? 1 : brightness) / 255f;
        }
        window.setAttributes(lp);
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (bleSuccess) {
            testItems.get(currentPosition).setCanTest(false);
            boolean testComplete = false;
            for (int i = 0; i < testItems.size(); i++) {
                if (testItems.get(i).isCanTest()) {
                    testComplete = false;
                    break;
                } else {
                    testComplete = true;
                }
            }
            final String testLog = testComplete ?
                    testType + "" + Contants.TEST_ITEM_BLUETOOTH + "\r\ntrue\r\n" : testType + "" + Contants.TEST_ITEM_BLUETOOTH + "\r\n";
            new Thread(new Runnable() {
                @Override
                public void run() {
                    FileUtils.writeFile(file_log.getAbsolutePath(), testLog);
                }
            }).start();
            if (mAdapter != null) {
                mAdapter.notifyDataSetChanged();
            }
            if (testComplete) {
                Intent mIntent = new Intent();
                Bundle bundle = new Bundle();
                bundle.putBoolean("result", true);
                mIntent.putExtras(bundle);
                TestItemActivity.this.setResult(testType, mIntent);
                finish();
            }
        }

    }
}
